package com.hducms.cms.service.impl;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;































import javax.print.DocFlavor.STRING;









//import javax.mail.MessagingException;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.facepp.error.FaceppParseException;
import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;
import com.hducms.cms.dao.CmsUserDao;
import com.hducms.cms.entity.main.Channel;
import com.hducms.cms.entity.main.CmsGroup;
import com.hducms.cms.entity.main.CmsUser;
import com.hducms.cms.entity.main.CmsUserExt;
import com.hducms.cms.entity.main.CmsUserSite;
import com.hducms.cms.service.ChannelService;
import com.hducms.cms.service.CmsGroupService;
import com.hducms.cms.service.CmsRoleService;
import com.hducms.cms.service.CmsUserExtService;
import com.hducms.cms.service.CmsUserService;
import com.hducms.cms.service.CmsUserSiteService;
import com.hducms.common.page.Pagination;
import com.hducms.common.util.FaceAddAdd;
//import com.jeecms.cms.dao.main.CmsUserDao;
//import com.jeecms.cms.entity.main.Channel;
//import com.jeecms.cms.entity.main.CmsGroup;
//import com.jeecms.cms.entity.main.CmsSite;
//import com.jeecms.cms.entity.main.CmsUser;
//import com.jeecms.cms.entity.main.CmsUserExt;
//import com.jeecms.cms.manager.main.ChannelMng;
//import com.jeecms.cms.manager.main.CmsGroupMng;
//import com.jeecms.cms.manager.main.CmsRoleMng;
//import com.jeecms.cms.manager.main.CmsSiteMng;
//import com.jeecms.cms.manager.main.CmsUserExtMng;
//import com.jeecms.cms.manager.main.CmsUserMng;
//import com.jeecms.cms.manager.main.CmsUserSiteMng;
//import com.jeecms.cms.manager.main.ContentMng;
//import com.jeecms.common.email.EmailSender;
//import com.jeecms.common.email.MessageTemplate;
//import com.jeecms.common.hibernate3.Updater;
//import com.jeecms.common.page.Pagination;
//import com.jeecms.core.entity.UnifiedUser;
//import com.jeecms.core.manager.UnifiedUserMng;
import com.hducms.core.entity.UnifiedUser;
import com.hducms.core.service.UnifiedUserService;

@Service
@Transactional
public class CmsUserServiceImpl implements CmsUserService {
	@Transactional(readOnly = true)
	public Pagination getPage(String username, String email, Integer siteId,
			Integer groupId, Boolean disabled, Boolean admin, Integer rank,
			int pageNo, int pageSize) {
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", username);
		map.put("email", email);
		map.put("groupId", groupId);
		map.put("disabled", disabled);
		map.put("admin", admin);
		map.put("rank", rank);
		map.put("pageSize", pageSize);
		Pagination page = new Pagination();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		map.put("start", page.getFirstResult());

		int totalCount = dao.countQueryResult(map);
		page.setTotalCount(totalCount);

		if (totalCount < 1) {
			page.setList(new ArrayList());
			return page;
		}
		
		List<CmsUser> list = dao.getPage(map);
		for (CmsUser cmsUser : list) {
			CmsUserExt temp = cmsUserExtMng.findById(cmsUser.getUserId());
			cmsUser.setUserExt(temp);
		}
		page.setList(list);
		
		return page;
	}
	
//	@Transactional(readOnly = true)
//	public List<CmsUser> getList(String username, String email, Integer siteId,
//			Integer groupId, Boolean disabled, Boolean admin, Integer rank) {
//		List<CmsUser> list = dao.getList(username, email, siteId, groupId,
//				disabled, admin, rank);
//		return list;
//	}
//
	@Transactional(readOnly = true)
	public List<CmsUser> getAdminList(Boolean allChannel,
			Boolean disabled, Integer rank) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (allChannel) {
			map.put("allChannel", 1);
		}
		if (disabled) {
			map.put("disabled", 1);
		}
		map.put("rank", rank);
		return dao.getAdminList(map);
	}

	@Transactional(readOnly = true)
	public CmsUser findById(Integer id) {
		CmsUser entity = dao.findById(id);
		return entity;
	}

	@Transactional(readOnly = true)
	public CmsUser findByUsername(String username) {
		CmsUser entity = dao.findByUsername(username);
		return entity;
	}

	public CmsUser registerMember(String username, String email,
			String password, String ip, Integer groupId, CmsUserExt userExt){
		UnifiedUser unifiedUser = unifiedUserMng.save(username, email,
				password, ip);
		CmsUser user = new CmsUser();
		user.forUser(unifiedUser);

		CmsGroup group = null;
		if (groupId != null) {
			group = cmsGroupMng.findById(groupId);
		} else {
			group = cmsGroupMng.getRegDef();
		}
		if (group == null) {
			throw new RuntimeException(
					"register default member group not found!");
		}
		user.setGroupId(groupId);
		user.setGroup(group);
		user.init();
		dao.save(user);
		cmsUserExtMng.save(userExt, user);
		return user;
	}
//
//	
//	public CmsUser registerMember(String username, String email,
//			String password, String ip, Integer groupId, CmsUserExt userExt,
//			Boolean activation, EmailSender sender, MessageTemplate msgTpl)throws UnsupportedEncodingException, MessagingException{
//		UnifiedUser unifiedUser = unifiedUserMng.save(username, email,
//				password, ip, activation, sender, msgTpl);
//		CmsUser user = new CmsUser();
//		user.forMember(unifiedUser);
//
//		CmsGroup group = null;
//		if (groupId != null) {
//			group = cmsGroupMng.findById(groupId);
//		} else {
//			group = cmsGroupMng.getRegDef();
//		}
//		if (group == null) {
//			throw new RuntimeException(
//					"register default member group not found!");
//		}
//		user.setGroup(group);
//		user.init();
//		dao.save(user);
//		cmsUserExtMng.save(userExt, user);
//		return user;
//	}
//
	public void updateLoginInfo(Integer userId, String ip) {
		Date now = new Timestamp(System.currentTimeMillis());
		CmsUser user = findById(userId);
		if (user != null) {
			user.setLoginCount(user.getLoginCount() + 1);
			user.setLastLoginIp(ip);
			user.setLastLoginTime(now);
		}
		dao.update(user);
	}

//	public void updateUploadSize(Integer userId, Integer size) {
//		CmsUser user = findById(userId);
//		user.setUploadTotal(user.getUploadTotal() + size);
//		if (user.getUploadDate() != null) {
//			if (CmsUser.isToday(user.getUploadDate())) {
//				size += user.getUploadSize();
//			}
//		}
//		user.setUploadDate(new java.sql.Date(System.currentTimeMillis()));
//		user.setUploadSize(size);
//	}
//	
//	public void updateUser(CmsUser user){
//		Updater<CmsUser>updater=new Updater<CmsUser>(user);
//		dao.updateByUpdater(updater);
//	}
//
//	public boolean isPasswordValid(Integer id, String password) {
//		return unifiedUserMng.isPasswordValid(id, password);
//	}
//
//	public void updatePwdEmail(Integer id, String password, String email) {
//		CmsUser user = findById(id);
//		if (!StringUtils.isBlank(email)) {
//			user.setEmail(email);
//		} else {
//			user.setEmail(null);
//		}
//		unifiedUserMng.update(id, password, email);
//	}
//
	public CmsUser saveAdmin(String username, String email, String password,
			String ip, boolean viewOnly, boolean selfAdmin, int rank,
			Integer groupId, Integer[] roleIds, Integer[] channelIds,
			Byte steps, Boolean allChannels,CmsUserExt userExt) {
		UnifiedUser unifiedUser = unifiedUserMng.save(username, email,
				password, ip);
		
		//新建一个管理员账户
		CmsUser user = new CmsUser();
		user.forAdmin(unifiedUser, viewOnly, selfAdmin, rank);
		
		CmsGroup group = null;
		if (groupId != null) {
			group = cmsGroupMng.findById(groupId);
		} else {
			group = cmsGroupMng.getRegDef();
		}
		if (group == null) {
			throw new RuntimeException(
					"register default member group not setted!");
		}
		user.setGroup(group);
		user.setGroupId(groupId);
		user.init();
		//数据库中保存简单用户信息，并且已经自动获得userId
		dao.save(user);
		//数据库中保存用户扩展信息
		cmsUserExtMng.save(userExt, user);
		
		/*保存用户角色信息*/
		if (roleIds != null) {
			saveUesrRole( user, roleIds);
		}
		
		/*保存用户栏目信息*/
		if (channelIds != null) {
			saveUesrChanelPermission(user, channelIds);
		}
		
		/*保存用户审核级别和是否拥有所有栏目的权限*/
		saveUesrSite(allChannels, user, steps);

//		if (siteIds != null) {
//			CmsSite site;
//			for (int i = 0, len = siteIds.length; i < len; i++) {
//				site = cmsSiteMng.findById(siteIds[i]);
//				cmsUserSiteMng.save(site, user, steps[i], allChannels[i]);
//			}
//		}
		return user;
	}
	

	/**
	 * 保存用户栏目信息
	 * @param user
	 * @param channelIds
	 */
	public void saveUesrRole(CmsUser user, Integer[]  roleIds){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", user.getUserId());
		List<Integer> list =  new ArrayList<Integer>();
		for (Integer rid : roleIds) {
			list.add(rid);
		}
		map.put("roleId", list);
		dao.insertUesrRole(map);
	}
	

	/**
	 * 保存用户栏目信息
	 * @param allChannels 
	 * @param user 
	 * @param user
	 * @param steps 
	 * @param channelIds
	 */
	public void saveUesrSite(Boolean allChannels, CmsUser user, Byte steps){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", user.getUserId());
		map.put("is_all_channel", allChannels);
		map.put("check_step", steps);
		dao.insertUesrSite(map);
	}
	
	/**
	 * 保存用户栏目信息
	 * @param user
	 * @param channelIds
	 */
	public void saveUesrChanelPermission(CmsUser user, Integer[]  channelIds){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", user.getUserId());
		List<Integer> list =  new ArrayList<Integer>();
		for (Integer cid : channelIds) {
			list.add(cid);
		}
		map.put("channelIds", list);
		dao.insertUesrChanelPermission(map);
	}
//
//	public void addSiteToUser(CmsUser user, CmsSite site, Byte checkStep) {
//		cmsUserSiteMng.save(site, user, checkStep, true);
//	}
//
//	public CmsUser updateAdmin(CmsUser bean, CmsUserExt ext, String password,
//			Integer groupId, Integer[] roleIds, Integer[] channelIds,
//			Integer siteId, Byte step, Boolean allChannel) {
//		CmsUser user = updateAdmin(bean, ext, password, groupId, roleIds,
//				channelIds);
//		// 更新所属站点
//		cmsUserSiteMng.updateByUser(user, siteId, step, allChannel);
//		return user;
//	}
//
	/**
	 * 更新管理员
	 * @param bean
	 * @param ext
	 * @param password
	 * @param groupId
	 * @param roleIds
	 * @param channelIds
	 * @param siteIds
	 * @param steps
	 * @param allChannels
	 * @return
	 */
//	public CmsUser updateAdmin(CmsUser bean, CmsUserExt ext, String password,
//			Integer groupId, Integer[] roleIds, Integer[] channelIds,
//			Integer[] siteIds, Byte[] steps, Boolean[] allChannels) {
//		CmsUser user = updateAdmin(bean, ext, password, groupId, roleIds,
//				channelIds);
//		// 更新所属站点
//		cmsUserSiteMng.updateByUser(user, siteIds, steps, allChannels);
//		return user;
//	}

	public CmsUser updateAdmin(CmsUser bean, CmsUserExt ext, String password, 
			Integer groupId, Integer[] roleIds, Integer[] channelIds,
			Byte steps, Boolean allChannels){
		CmsUser user = dao.findById(bean.getUserId());

		if (groupId != null) {
			bean.setGroupId(groupId);
		}
		
		dao.update(bean);//更新用户基本资料
		cmsUserExtMng.update(ext, bean);//更新用户扩展资料
		
		/* 更新角色*/
		if (roleIds != null) {
			dao.deleteUesrRoleByUserId(user.getUserId());
			saveUesrRole( user, roleIds);
		}
		
		/* 更新栏目权限*/
		if (channelIds != null) {
			// 清除
			dao.deleteUesrChanelPermissionByUserId(user.getUserId());
			// 添加
			saveUesrChanelPermission(user, channelIds);
		}
		
		CmsUserSite cmsUserSite = new CmsUserSite(bean.getUserId(),steps,allChannels);
		cmsUserSiteMng.update(cmsUserSite);
	
		unifiedUserMng.update(bean.getUserId(), password, bean.getEmail());
		return user;
	}

	public CmsUser updateMember(Integer id, String email, String password,
			Boolean isDisabled, CmsUserExt ext, Integer groupId) {
		CmsUser entity = findById(id);
		if (!StringUtils.isBlank(email)) {
			entity.setEmail(email);
		}
		if (isDisabled != null) {
			entity.setIsDisabled(isDisabled);
		}
		if (groupId != null) {
			entity.setGroupId(groupId);
			entity.setGroup(cmsGroupMng.findById(groupId));
		}
		dao.update(entity);
		cmsUserExtMng.update(ext, entity);
		unifiedUserMng.update(id, password, email);
		return entity;
	}
//	
//	public CmsUser updateUserConllection(CmsUser user,Integer cid,Integer operate){
//		Updater<CmsUser> updater = new Updater<CmsUser>(user);
//		user = dao.updateByUpdater(updater);
//		if (operate.equals(1)) {
//			user.addToCollection(contentMng.findById(cid));
//		}// 取消收藏
//		else if (operate.equals(0)) {
//			user.delFromCollection(contentMng.findById(cid));
//		}
//		return user;
//	}
//
	public CmsUser deleteById(Integer id) {
		//######################删除face++ 内的person
		HttpRequests httpRequests = faceAddAdd.getTool(); //face++ 工具
		CmsUser bean = dao.findById(id);
		String username = bean.getUsername();
		try {
			httpRequests.personDelete(new PostParameters().setPersonName(username));
		} catch (FaceppParseException e) {
			System.out.println("face++删除不成功");
		}
		//##########################################
		unifiedUserMng.deleteById(id);
		dao.deleteUesrChanelPermissionByUserId(id);
		dao.deleteUesrRoleByUserId(id);
		//删除用户user信息
		dao.deleteById(id);
		
		return bean;
		//由于设置了外键，userExt信息自动删除

//		//删除收藏信息
//		bean.clearCollection();
	}

	public CmsUser[] deleteByIds(Integer[] ids) {
		CmsUser[] beans = new CmsUser[ids.length];
		for (int i = 0, len = ids.length; i < len; i++) {
			beans[i]=deleteById(ids[i]);
		}
		return beans;
	}

	public boolean usernameNotExist(String username) {
		return dao.countByUsername(username) <= 0;
	}
//	
//	public boolean usernameNotExistInMember(String username){
//		return dao.countMemberByUsername(username)<= 0;
//	}
//
	public boolean emailNotExist(String email) {
		return dao.countByEmail(email) <= 0;
	}
	@Override
	public List<CmsUser> findByGroupId(Integer id) {
			
		return dao.findByGroupId(id);
	}
	/**
	 * 明显是重置人脸信息啊
	 * @param id
	 */
	public void resetFaceById(Integer id) {
		//######################删除face++ 内的person
		HttpRequests httpRequests = faceAddAdd.getTool(); //face++ 工具
		CmsUser user = dao.findById(id);
		CmsUserExt userE = cmsUserExtMng.findById(id);
		if (userE.getUserFace()!=null || userE.getUserFace()!="") {
			String username = user.getUsername();
			try {
				httpRequests.personDelete(new PostParameters().setPersonName(username));
			} catch (FaceppParseException e) {
				System.out.println("face++删除不成功");
			}
		}
		//########################################## 
		dao.resetFaceById(id);
	}
	@Override
	public void resetFaceByIds(Integer[] ids) {
		for (int i = 0, len = ids.length; i < len; i++) {
			resetFaceById(ids[i]);
		}
	}
	
	@Override
	public void updatePushId(String pCId, String pUId,int userId) {
		Map<String, Object> param = new HashMap<>();
		param.put("pUId", pUId);
		param.put("pCId", pCId);
		param.put("userId", userId);
		dao.updatePushId(param);
	}
	
	@Override
	public void updateGetuiClientId(String clientId, Integer userId) {

		Map<String, Object> param = new HashMap<>();
		param.put("clientId", clientId);
		param.put("userId", userId);
		dao.updateGetuiClientId(param);
	}
	
	@Override
	public void updatePatternLock(Integer userId, String passw) {
		Map<String, Object> param = new HashMap<>();
		param.put("passw", passw);
		param.put("userId", userId);
		dao.updatePatternLock(param);
	}
	
	@Autowired
	private CmsUserSiteService cmsUserSiteMng;
//	private CmsSiteMng cmsSiteMng;
	private ChannelService channelMng;
	private CmsRoleService cmsRoleMng;
	private CmsGroupService cmsGroupMng;
	private UnifiedUserService unifiedUserMng;
	private CmsUserExtService cmsUserExtMng;
	private CmsUserDao dao;
	@Autowired
	private FaceAddAdd faceAddAdd;
//	@Autowired
//	private ContentMng contentMng;

//	@Autowired
//	public void setCmsUserSiteMng(CmsUserSiteMng cmsUserSiteMng) {
//		this.cmsUserSiteMng = cmsUserSiteMng;
//	}
//
//	@Autowired
//	public void setCmsSiteMng(CmsSiteMng cmsSiteMng) {
//		this.cmsSiteMng = cmsSiteMng;
//	}
//
//	@Autowired
//	public void setChannelMng(ChannelMng channelMng) {
//		this.channelMng = channelMng;
//	}
//
//	@Autowired
//	public void setCmsRoleMng(CmsRoleMng cmsRoleMng) {
//		this.cmsRoleMng = cmsRoleMng;
//	}
//
	@Autowired
	public void setUnifiedUserMng(UnifiedUserService unifiedUserMng) {
		this.unifiedUserMng = unifiedUserMng;
	}

	@Autowired
	public void setCmsUserExtMng(CmsUserExtService cmsUserExtMng) {
		this.cmsUserExtMng = cmsUserExtMng;
	}

	@Autowired
	public void setCmsGroupMng(CmsGroupService cmsGroupMng) {
		this.cmsGroupMng = cmsGroupMng;
	}

	@Autowired
	public void setDao(CmsUserDao dao) {
		this.dao = dao;
	}



}